package com.bstek.xxl.job.admin.controller.interceptor;

import com.bstek.bdf2.core.business.IUser;
import com.bstek.bdf2.core.context.ContextHolder;
import com.bstek.bdf2.core.security.ISecurityInterceptor;
import com.bstek.bdf2.core.security.SecurityInterceptorAdapter;
import com.bstek.xxl.job.admin.core.model.XxlJobUser;
import com.bstek.xxl.job.admin.core.util.CookieUtil;
import com.bstek.xxl.job.admin.core.util.JacksonUtil;
import com.bstek.xxl.job.admin.dao.XxlJobUserDao;
import com.bstek.xxl.job.admin.service.LoginService;
import org.springframework.security.web.context.HttpRequestResponseHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigInteger;

/**
 * @Title: XxlJobSecurityInterceptorAdapter
 * @Package: com.bstek.xxl.job.admin.controller.interceptor
 * @Description:
 * @Author: zxq
 * @Date: 2023/12/6 - 10:18
 */

@Service
public class XxlJobISecurityInterceptorImpl implements ISecurityInterceptor {
    public static final String LOGIN_IDENTITY_KEY = "XXL_JOB_LOGIN_IDENTITY";

    @Override
    public void beforeLogin(HttpRequestResponseHolder holder) {

    }
    @Resource
    private XxlJobUserDao xxlJobUserDao;
    @Override
    public void loginSuccess(HttpRequestResponseHolder holder) {
        IUser user= ContextHolder.getLoginUser();
        if(user!=null){
            String username = user.getUsername();
            XxlJobUser xxlJobUser = xxlJobUserDao.loadByUserName(username);
            String tokenJson = JacksonUtil.writeValueAsString(xxlJobUser);
            String loginToken = new BigInteger(tokenJson.getBytes()).toString(16);
            HttpServletRequest request = holder.getRequest();
            HttpServletResponse response = holder.getResponse();
            request.setAttribute(LoginService.LOGIN_IDENTITY_KEY, xxlJobUser);
            CookieUtil.set(response, LOGIN_IDENTITY_KEY, loginToken, true);

         }

    }

    @Override
    public void loginFailure(HttpRequestResponseHolder holder) {

    }

    @Override
    public void beforeAuthorization(HttpRequestResponseHolder holder) {
//        System.out.println("用户在访问系统资源时(比如访问某URL)，系统安全模块对用户进行授权之前需要处理的动作");

    }

    @Override
    public void authorizationSuccess(HttpRequestResponseHolder holder) {
//        System.out.println("用户在访问系统资源时(比如访问某URL)，系统安全模块对用户进行授权成功之后需要处理的动作");

    }

    @Override
    public void authorizationFailure(HttpRequestResponseHolder holder) {
//        System.out.println("用户在访问系统资源时(比如访问某URL或某模块)，系统安全模块对用户进行授权失败之后需要处理的动作");
    }
}
